package com.qing.simple_player.viewmodel;

import android.util.Log;

import androidx.annotation.CallSuper;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.ViewModel;
import androidx.media3.common.MediaItem;
import androidx.media3.common.MediaMetadata;

import com.qing.simple_player.player.IPlayer;

/**
 * 播放器ViewModel的抽象父类
 */
public abstract class AbsPlayerViewModel extends ViewModel implements IPlayer {

    protected static final String TAG = "AbsPlayerViewModel";
    protected static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
    private static final String ASSETS_PREFIX = "file:///android_asset/";
    private static final String ASSETS_TAG = "asset:";
    protected String CHILD_TAG = initChildTag();

    public static boolean isReady(@PlaySate int state) {
        return state != PLAY_STATE_IDLE && state != PLAY_STATE_BUFFERING && state != PLAY_STATE_ENDED;
    }

    @NonNull
    public static MediaItem buildMediaItem(@NonNull String url, @Nullable String title, @Nullable String artist) {
        if (url.startsWith(ASSETS_TAG)) {
            url = url.replace(ASSETS_TAG, ASSETS_PREFIX);
        }
        return new MediaItem.Builder()
                .setUri(url)
                .setMediaMetadata(new MediaMetadata.Builder().setTitle(title).setArtist(artist).build())
                .build();
    }

    @NonNull
    public static MediaItem buildMediaItem(@NonNull String url, @Nullable String title) {
        return buildMediaItem(url, title, null);
    }

    @NonNull
    public static MediaItem buildMediaItem(@NonNull String url) {
        return buildMediaItem(url, null, null);
    }

    /**
     * 初始化子类 TAG
     *
     * @return 子类 TAG
     */
    protected String initChildTag() {
        return getClass().getSimpleName();
    }

    /**
     * 获取播放状态的 LiveData。
     *
     * @return 播放状态的 LiveData。
     */
    public abstract LiveData<Integer> getPlaybackState();

    /**
     * 获取播放进度的 LiveData。
     *
     * @return 播放进度的 LiveData。
     */
    public abstract LiveData<Long> getPlayProgress();

    /**
     * 获取播放时长的 LiveData。
     *
     * @return 播放时长的 LiveData。
     */
    public abstract LiveData<Long> getPlayDuration();

    @Override
    @CallSuper
    protected void onCleared() {
        super.onCleared();
        release();
    }
}
